package com.rocky.study.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 主线程等待子线程完成
 * @Author: rocky
 */
public class MasterWaitSon {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(8);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 8; i++) {
            executorService.submit(new WorkerRunnable(i,countDownLatch));
        }
        long begin = System.currentTimeMillis();
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("一共耗时: " + (end - begin) + "ms");
    }

    public static class WorkerRunnable implements Runnable {

        private CountDownLatch latch;

        private int id;

        public WorkerRunnable(int id,CountDownLatch latch) {
            this.latch = latch;
            this.id    = id;
        }

        @Override
        public void run() {
            runWork();
        }

        public void runWork() {
            System.out.println("编号" + id + " 开始执行");
            try {
                TimeUnit.MILLISECONDS.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
            System.out.println("编号:" + id + " 执行结束");
        }

    }
}
